package com.htjx.mall.services.wallet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.htjx.mall.commons.mappers.AccountMapper;
import com.htjx.mall.commons.models.enums.SeqType;
import com.htjx.mall.commons.models.user.Account;
import com.htjx.mall.services.SequenceManager;

@Service
public class AccountService {
	@Autowired
	private AccountMapper accountMapper;
	@Autowired
	private SequenceManager sequenceManager;
	@Autowired
	private TransactionTemplate transactionTemplate;
	
	public void insertOne(final Account account) {
		long[] seq = sequenceManager.buildBatchSeq(SeqType.Ticket, 1);
		account.setId(seq[0]);
		transactionTemplate.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				accountMapper.insertOne(account);
			}
		});
	}
	
	public void updateOne(final Account account) {
		transactionTemplate.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				accountMapper.updateOne(account);
			}
		});
	}
	
	public Account selectOne(long user_id) {
		Account account = accountMapper.selectOne(user_id);
		if(account == null) {
			account = new Account();
			account.setUser_id(user_id);
			insertOne(account);
			return accountMapper.selectOne(user_id);
		}
		return account;
	}
}
